package com.hzt.service;

import com.alibaba.fastjson.JSON;
import com.hzt.entity.Content;
import com.hzt.utils.HtmlParseUtils;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.Highlighter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 功能描述: 
 * @author: huangzhitao
 * @date: 2021/3/21 3:37 上午
 */
@Service
public class ContentService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public Boolean  parseContent(String keyword) throws Exception {
        //查看此索引库是否存在
        GetIndexRequest request = new GetIndexRequest("jd_goods");
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        //不存在则创建
        if(exists!=true){
            CreateIndexRequest request1 = new CreateIndexRequest("jd_goods");
            CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request1, RequestOptions.DEFAULT);
        }
        List<Content> list=new  HtmlParseUtils().parseJD(keyword);
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i = 0; i < list.size(); i++) {
                bulkRequest.add(
                        new IndexRequest("jd_goods").
                                source(JSON.toJSONString(list.get(i)), XContentType.JSON)
                );
        }
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return  !bulkResponse.hasFailures();
    }

    //获取数据实现搜索功能
    public List<Map<String,Object>> searchPage(String keyword,int pageNo,int pageSize) throws IOException {
            if(pageNo<1){
                pageNo=1;
            }
            //条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit documentFields : search.getHits().getHits()) {
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            list.add(sourceAsMap);
        }
        return list;
    }

    //获取数据实现搜索功能 高亮显示
    public List<Map<String,Object>> searchHightLightPage(String keyword,int pageNo,int pageSize) throws IOException {
        if(pageNo<1){
            pageNo=1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false);//同一个标题多个高亮只显示一个
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit documentFields : search.getHits().getHits()) {

            Map<String, HighlightField> fields = documentFields.getHighlightFields();
            HighlightField title = fields.get("title");

            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            //解析高亮的字段,就是将原来的字段替换成我们高亮的字段即可
            if(title!=null){
                Text[] fragments = title.getFragments();//获取高亮的字段
                String n_title="";
                for (Text fragment : fragments) {
                    n_title +=fragment;
                }
                sourceAsMap.put("title",n_title);
            }
            list.add(sourceAsMap);
        }
        return list;
    }

}